package com.xmc.servlet;


import com.xmc.dao.CourseDao;
import com.xmc.dao.UserDao;
import com.xmc.pojo.Course;
import com.xmc.pojo.CourseMsg;
import com.xmc.pojo.User;
import com.xmc.pojo.vo.CountResult;
import com.xmc.pojo.vo.PonitResult;
import com.xmc.utils.BaseContext;
import com.xmc.utils.HttpClientUtils;
import com.xmc.utils.Result;
import com.xmc.utils.ResultWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 谢孟呈
 */
@WebServlet(name = "userServlet",urlPatterns = "/user/*")
public class UserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = BaseContext.getAction(req.getRequestURI());
        User user = BaseContext.getCurrentUser(req);
        String code = req.getParameter("username");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        boolean isSuccess = false;

        //学生和老师共同操作
        if (action.equals("login")){
            User userinfo = new UserDao().login(code, password, role);
            System.out.println("0000000000000000");
            System.out.println(userinfo);
            System.out.println("0000000000000000");
            if (userinfo != null){
                req.getSession().setAttribute("user",userinfo);
                Result res = new Result(true,"登录成功");
                ResultWriter.write(resp, res);
            }else {
                Result res = new Result(false,"登录失败，账号或密码错误!");
                ResultWriter.occurException(resp,res);
            }
        }
        if (action.equals("logout")){
            req.getSession().invalidate();
            System.out.println(req.getSession().getAttribute("user"));
            resp.sendRedirect("/MyStudentMaster_war/login.jsp");
        }
        if (action.equals("updatesession")){
            User userInfo = new UserDao().login(user.getCode(),null,null);
            req.getSession().setAttribute("user",userInfo);
            Result res = new Result(true,"登录成功");
            ResultWriter.write(resp, res);
        }
        if (action.equals("updateUser")){
            int stuId = Integer.parseInt(req.getParameter("stuId"));
            Long phone = Long.parseLong(req.getParameter("stuPhone"));
            String email = req.getParameter("stuEmail");
            isSuccess = new UserDao().updateStudent(stuId,phone,email,null);
            if (isSuccess) {
                Result res = new Result(true, "更新成功");
                ResultWriter.write(resp,res);
            }
        }
        if (action.equals("updateUserPassWord")){
            String newPassword = req.getParameter("newPassword");
            String stuPassword = req.getParameter("stuPassword");
            boolean b = new UserDao().checkPwd(user.getId(), stuPassword);
            if (!b){
                Result res = new Result(false, "");
                ResultWriter.write(resp,res);
                return;
            }
            isSuccess = new UserDao().updateStudent(user.getId(),null,null,newPassword);
            if (isSuccess) {
                Result res = new Result(true, "更新成功");
                ResultWriter.write(resp,res);
            }
        }
        if(action.equals("Statisticians")){
                req.getRequestDispatcher("/index.jsp").forward(req,resp);

        }
        if(action.equals("getEchartsServlet")){
            if (user.getRole()==1){
                List<Course> myGrade = new CourseDao().getMyGrade(user.getCode(), null, null);
                //保存绩点，课程名，总学分返回前端
                List<PonitResult> ponitResultList = new ArrayList<>();

                //获取总学分
                float countXf = 0;
                float toltalPoint = 0;
                for (int i = 0; i < myGrade.size(); i++) {
                    countXf += Float.parseFloat(myGrade.get(i).getCoursexf());
                }

                //
                for (int i = 0; i < myGrade.size(); i++) {
                    PonitResult ponitResult = new PonitResult();
                    ponitResult.setCoursename(myGrade.get(i).getCoursename());
                    if (myGrade.get(i).getTotalgrade() >=60){
                        //绩点=分数/10-5
                        float point = (myGrade.get(i).getTotalgrade()/10) -5;
                        //平均绩点（每门课程的学分数×对应课程的绩点）的总和÷学分的总和
                        float avgPonit = ((Float.parseFloat(myGrade.get(i).getCoursexf()))*point)/countXf;
                        toltalPoint +=avgPonit;
                        //设置学分
                        ponitResult.setAvgpoint(String.valueOf(avgPonit));
                    }else if (myGrade.get(i).getTotalgrade() < 60 &&myGrade.get(i).getTotalgrade() >0){
                        //小于60没绩点
                        ponitResult.setAvgpoint("0");
                    }else {
                        ponitResult.setAvgpoint("0");
                    }
                    ponitResultList.add(ponitResult);
                }
                ponitResultList.get(0).setToltalpoint(toltalPoint);

                Result res = new Result(true, "1",ponitResultList);
                ResultWriter.write(resp,res);
            }
            if (user.getRole()==2) {
                Float count = 0f;
                int maxScore = 0;
                Float avgScore = 0f;
                int minimumScore =100;
                Float passingRate = 0f;
                int NumberFailedSubjects = 0;
                List<CountResult> countResultList = new ArrayList<>();
                List<Course> myGrade = new CourseDao().getMyGrade(null, null, user.getUsername());
                //去重
                for (int i = 0; i < myGrade.size(); i++) {
                    for (int j = i + 1; j < myGrade.size(); j++) {
                        if (myGrade.get(i).getCoursename().equals(myGrade.get(j).getCoursename())) {
                            myGrade.remove(j);
                            j--;
                        }
                    }
                }
                //保存课程名称

                for (int i = 0; i < myGrade.size(); i++) {
                    CountResult countResult = new CountResult();
                    countResult.setCourseName(myGrade.get(i).getCoursename());
                    List<Course> myGrade2 = new CourseDao().getMyGrade(null, myGrade.get(i).getCoursename(), user.getUsername());
                    System.out.println("-------------------------");
                    int total = myGrade2.size();
                    for (int j = 0; j < myGrade2.size(); j++) {

                        if (minimumScore > myGrade2.get(j).getTotalgrade()){
                            minimumScore = myGrade2.get(j).getTotalgrade();
                        }
                        if (maxScore < myGrade2.get(j).getTotalgrade()){
                            maxScore = myGrade2.get(j).getTotalgrade();
                        }

                        if (myGrade2.get(j).getTotalgrade() >= 60){
                            avgScore += myGrade2.get(j).getTotalgrade();
                            count++;
                        }
                        if (myGrade2.get(j).getTotalgrade() < 60){
                            NumberFailedSubjects++;
                            avgScore += myGrade2.get(j).getTotalgrade();
                        }
                        if (myGrade2.get(j).getTotalgrade() < 0){
                            myGrade2.get(j).setTotalgrade(60);
                        }

                    }
                    System.out.println("总共"+total);
                    passingRate = count/total;
                    avgScore = avgScore/total;
                    countResult.setMinimumScore(minimumScore);
                    countResult.setHighestScore(maxScore);
                    countResult.setNumberFailedSubjects(NumberFailedSubjects);
                    countResult.setAvgScore(avgScore);
                    countResult.setPassingRate(passingRate);
                    countResultList.add(countResult);

                    //重置
                     count = 0f;
                     maxScore = 0;
                     avgScore = 0f;
                     minimumScore =100;
                     passingRate = 0f;
                     NumberFailedSubjects = 0;
                }
                Result res = new Result(true, "2",countResultList);
                ResultWriter.write(resp,res);

            }

        }

        //学生操作
        if (action.equals("getCourse")){
            boolean b = new CourseDao().checkCourseInit(user.getCode());
            //已经加载过了
            if (b){
                Result res = new Result(true, "更新成功");
                ResultWriter.write(resp,res);
                return;
            }
            try {
                //未加载过,获取cookie
                String cookie = BaseContext.getCookie();
                if (cookie != null){
                    //模拟登录
                    BaseContext.toLogin(user,cookie);
                    //获取课程信息
                    List<Course> courses = BaseContext.CourseList(cookie,user.getCode());
                    for (int i = 0; i < courses.size(); i++) {
                        for (int j = i + 1; j < courses.size(); j++) {
                            if (courses.get(i).getCourseid().equals(courses.get(j).getCourseid())) {
                                courses.remove(j);
                                j--;
                            }
                        }
                    }
                    //获取课表信息,1-19周,并且存到数据库
                    for (int i = 1; i < 19; i++) {
                        String info = HttpClientUtils.sentGet("https://jwxt.gdupt.edu.cn/xsgrkbcx!getKbRq.action?xnxqdm=202201&zc="+i, cookie);
                        List<CourseMsg> cours = BaseContext.toCourseResult(info, user.getCode());
                        for (int i1 = 0; i1 < cours.size(); i1++) {
                            new CourseDao().createCourseMsg(cours.get(i1));
                        }
                    }
                    //将这个学期的全部课程信息存到数据库
                    for (Course course : courses) {
                        new CourseDao().createCourse(course);
                    }

                }

                Result res = new Result(true, "");
                ResultWriter.write(resp,res);
                return;
            }catch (Exception e){
                //由于网络请求失败,删除延迟插入的数据
                new CourseDao().deleteCourseMsg(user.getCode());
                new CourseDao().deleteCourse(user.getCode());
                Result res = new Result(false, "");
                ResultWriter.write(resp,res);
            }

        }
        if (action.equals("getAllCourse")){
            String zhouci= req.getParameter("zhouci");
            List<CourseMsg> courseMsgList = new CourseDao().getAllCourse(zhouci,user.getCode());
            if (courseMsgList.size() == 0){
                CourseMsg courseMsg = new CourseMsg();
                courseMsg.setZhouci(zhouci);
                courseMsgList.add(courseMsg);
            }
            req.setAttribute("courseMsgList",courseMsgList);
            req.getRequestDispatcher("/student/student-course.jsp").forward(req,resp);

        }
        if (action.equals("getMyGrade")){
            List<Course> courseList = new CourseDao().getMyGrade(user.getCode(),null,null);
            req.setAttribute("courseList",courseList);
            req.getRequestDispatcher("/student/student-grade.jsp").forward(req,resp);

        }
        if (action.equals("getCourseForName")){
            String coursename= req.getParameter("coursename");
            System.out.println(coursename);
            List<Course> courseList = new CourseDao().getMyGrade(user.getCode(),coursename,null);
            req.setAttribute("courseList",courseList);
            req.getRequestDispatcher("/student/student-grade.jsp").forward(req,resp);
        }

        //老师操作
        if (action.equals("getTeacherTask")){
            List<Course> courseList = new CourseDao().getMyGrade(null,null,user.getUsername());
            for (int i = 0; i < courseList.size(); i++) {
                for (int j = i + 1; j < courseList.size(); j++) {
                    if (courseList.get(i).getCourseid().equals(courseList.get(j).getCourseid())) {
                        courseList.remove(j);
                        j--;
                    }
                }
            }
            req.setAttribute("courseList",courseList);
            req.getRequestDispatcher("/teacher/teacher-task.jsp").forward(req,resp);
        }
        if (action.equals("getCourseAndStudent")){
            List<Course> courseList = new CourseDao().getMyGrade(null,null,user.getUsername());
            //将学生id转成学生名字
            for (int i = 0; i < courseList.size(); i++) {
                User user1 = new UserDao().login(courseList.get(i).getStudentid(),null,null);
                courseList.get(i).setStudentid(user1.getUsername());
            }
            System.out.println(courseList);
            req.setAttribute("courseList",courseList);
            req.getRequestDispatcher("/teacher/teacher-grade.jsp").forward(req,resp);
        }
        if (action.equals("getScById")){

            String studentname= req.getParameter("studentId");
            String coursename= req.getParameter("coursename");

            String studentId =  new UserDao().getUserIdByUsername(studentname);
            List<Course> courseList = new CourseDao().getMyGrade(studentId,coursename,user.getUsername());
            Result res = new Result(true, "更新成功",courseList.get(0));
            ResultWriter.write(resp,res);
            return;
        }
        if (action.equals("updateScoreByTeacherAndStudentId")){
            String studentname= req.getParameter("studentId");
            String coursename= req.getParameter("coursename");
            float usualgrades= Float.parseFloat(req.getParameter("usualgrades"));
            float examgrade= Float.parseFloat(req.getParameter("examgrade"));
            int totalgrade= Integer.parseInt(req.getParameter("totalgrade"));
            String studentId =  new UserDao().getUserIdByUsername(studentname);


            boolean b =  new UserDao().updateScoreByTeacherAndStudentId(studentId,usualgrades,examgrade,totalgrade,coursename);
            Result res = new Result(true, "更新成功");
            ResultWriter.write(resp,res);
            return;
        }



    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
